package top.lingkang.potato.controller;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import javafx.application.Platform;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
import org.controlsfx.control.MaskerPane;
import org.controlsfx.control.Notifications;
import org.controlsfx.control.PopOver;
import top.lingkang.potato.StateManager;
import top.lingkang.potato.config.UserHomeConfig;
import top.lingkang.potato.constants.ConfigConstants;
import top.lingkang.potato.constants.HttpConstants;
import top.lingkang.potato.dto.ResponseResult;
import top.lingkang.potato.network.HttpRequest;
import top.lingkang.potato.utils.rx.RxObservableUtils;
import top.lingkang.potato.utils.rx.Watch;
import top.lingkang.potato.views.HomeView;
import top.lingkang.potato.views.LoginView;
import top.lingkang.potato.vo.UserInfoVo;

import java.net.URL;
import java.util.Properties;
import java.util.ResourceBundle;

public class LoginController implements Initializable {

    @FXML
    private Button loginButton;
    @FXML
    private TextField username, password;
    @FXML
    private CheckBox autoLogin, rememberMe;

    private static final String auto = "autoLogin", remember = "rememberMe";

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        Properties property = UserHomeConfig.getProperty();
        PopOver popOver = new PopOver();
        if (StrUtil.isNotEmpty(property.getProperty(remember))) {
            rememberMe.setSelected(true);
            password.setText(property.getProperty(ConfigConstants.LAST_ACCESS_TOKEN));
        }

        String lastAccess = property.getProperty(ConfigConstants.LAST_ACCESS_USERNAME);
        if (!StrUtil.isEmpty(lastAccess)) {
            username.setText(lastAccess);
        }

        if ("true".equals(property.getProperty(auto))) {
            autoLogin.setSelected(true);
            if (StrUtil.isNotEmpty(UserHomeConfig.getProperty().getProperty(ConfigConstants.LAST_ACCESS_TOKEN)))
                login(loginButton, username, password, null, null);
        }

        loginButton.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent actionEvent) {
                CharSequence user = username.getCharacters();
                if (StrUtil.isEmpty(user)) {
                    popOver.setContentNode(new Label("账号不能为空！"));
                    popOver.show(username);
                    return;
                }

                CharSequence pwd = password.getCharacters();
                if (StrUtil.isEmpty(pwd)) {
                    popOver.setContentNode(new Label("密码不能为空！"));
                    popOver.show(password);
                    return;
                }

                System.out.println("你点击了我！" + user);
                login(loginButton, username, password, user.toString(), pwd.toString());
            }
        });

        autoLogin.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent actionEvent) {
                UserHomeConfig.setProperties(auto, autoLogin.isSelected() ? "true" : "false");
            }
        });

        rememberMe.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent actionEvent) {
                UserHomeConfig.setProperties(remember, rememberMe.isSelected() ? "true" : "false");
            }
        });
    }

    private static void login(Button loginButton, TextField username,
                              TextField password, String user, String pwd) {
        new RxObservableUtils(new ObservableOnSubscribe() {
            @Override
            public void subscribe(ObservableEmitter emitter) throws Exception {
                LoginView.showLoginMaskerPane.set(true);
                ResponseResult login;
                String property = UserHomeConfig.getProperty().getProperty(ConfigConstants.LAST_ACCESS_TOKEN);
                if (StrUtil.isNotEmpty(property) && "true".equals(UserHomeConfig.getProperty().getProperty(remember))) {
                    login = HttpRequest.accountClient.login_token(property);
                } else {
                    login = HttpRequest.accountClient.login(user, pwd);
                }
                emitter.onNext(login);
                emitter.onComplete();
            }
        }, new Watch() {
            @Override
            public void onNext(Object o) {
                ResponseResult login = (ResponseResult) o;
                if (login.getCode() != HttpConstants.OK) {
                    PopOver popOver = new PopOver();
                    popOver.setContentNode(new Label(login.getMessage()));
                    if (login.getMessage().indexOf("账号") != -1) {
                        popOver.show(username);
                    } else if (login.getMessage().indexOf("密码") != -1) {
                        popOver.show(password);
                    } else if (login.getMessage().indexOf("还未") != -1) {
                        popOver.setContentNode(new Label("授权已经过期！请重新登录。"));
                        popOver.show(password);
                        password.setText("");
                        UserHomeConfig.setProperties(ConfigConstants.LAST_ACCESS_TOKEN, "");
                    } else {
                        popOver.show(loginButton);
                    }
                    return;
                }

                JSONObject data = (JSONObject) login.getData();
                System.out.println(data.get("token"));
                StateManager.token = data.getString("token");
                StateManager.userInfoVo = data.getObject(ConfigConstants.USER_INFO, UserInfoVo.class);
                UserHomeConfig.setUserProperties(StateManager.userInfoVo.getUsername(),
                        JSONObject.toJSONString(StateManager.userInfoVo));

                UserHomeConfig.setProperties(ConfigConstants.LAST_ACCESS_USERNAME, StateManager.userInfoVo.getUsername());
                UserHomeConfig.setProperties(ConfigConstants.LAST_ACCESS_TOKEN, StateManager.token);

                // 显示主页
                StateManager.stageManager.put("HomeView", new HomeView());

                LoginView.showLoginMaskerPane.set(false);
                // 关闭登录页面
                StateManager.stageManager.get("LoginView").close();
                StateManager.stageManager.remove("LoginView");
            }

            @Override
            public void onError(Throwable e) {
                PopOver popOver = new PopOver();
                popOver.setContentNode(new Label("登录服务器异常"));
                popOver.show(loginButton);
                Notifications notifications = Notifications.create();
                notifications.title("错误");
                notifications.text("登录服务器错误！");
                notifications.show();
                LoginView.showLoginMaskerPane.set(false);
            }

            @Override
            public void onComplete() {
                LoginView.showLoginMaskerPane.set(false);
            }
        });
    }
}
